package com.csj.mvvm.algorithm;


import android.util.Base64;
import android.util.Log;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

//implementation 'io.jsonwebtoken:jjwt:0.9.1'
public class JWT {
    private static String publicKey = "";

    private static String privateKey =
            "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMKJGXSQoa6hjy1EeE6gi+AUWbbHvGupYUSqWVS+fOfbfgmaUT8zGhpCmW31FwbJCVjaXDkmpjohIKKErE+BpE8r/qjPDPM+/nlEA53bbwICuBk6b4f4r6x+prdnsVOwt6nGiKXhNW5xuJLVjMVGKljO8JCOQlyWKyPZj9rreRv9AgMBAAECgYEAwn/7EH2O+iAUHAlqVArW7zrJnCNFs0sNsm6zlDREhDkDYiyFcS/xuDHAX5z94c3c55ajQIzxBAudKoCGG5QeJz4qrmS0jgLvAs9mTmTu86pEXZ+hsRPWa+atcvioDc8siva1hOclsq2sBjoZRgYcnIUAhifO+fr4XKnlOwBSlWECQQD1dJ4cidmkXfS/hcNeBWXQWkPKFA494I1B8Nb5ZsgN/zvqSIxNjVBxelN+Lnxc/N9uXTeFuhwOUPIKb0qN8De5AkEAyuR+BhS+JTVzLFXy+zmric6PZFmk8SL1Gc0GxtVTIhCMglDAriun08uihIG5T589omUh49SLBRs7+E5wcJwgZQJBAJMIanY59U/KoIPhwugdX6HxkE4KuYVDcBqiBISdlxUbYW60SqdiEWAIoN8jRYgGSmk4GbxXgdrpjjPF+ukPjrECQH8LVnJeWLYZ4vV3GEABW41d/2HZ1DN+LTWrsTud5oFlFWagRBaLlXpEf44zYKMf1ksywmbT9v0KkaGpFDUfPhUCQEmb2Pze3jlX6ymCj2UrCNotNzzhVByn9J0/QJt0kMzoQRp3UScIHMIl0mpHfPbFR/ynfY1FpK32CwbVgulrZl8=";

    public static String JWTGenerate(String id, String name, String time) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", id);
        map.put("display_name", name);
        map.put("exp", time);
        String compactJws = Jwts.builder().addClaims(map).setHeaderParam("typ", "JWT")
                .signWith(SignatureAlgorithm.RS256, getRSAPrivateKey(privateKey)).compact();
        return compactJws;
    }

    public static void JWTParse(String jwt) {
        //在解析的时候一定要传key进去，否则无法通过key的认证
        Jwt parse = Jwts.parser().setSigningKey(getRSAPublicKey(publicKey)).parseClaimsJws(jwt);
        Map<String, Object> map = (Map<String, Object>) parse.getBody();
        Log.e("JWT", "user_id=" + map.get("user_id").toString());
        Log.e("JWT", "display_name=" + map.get("display_name").toString());
    }

    /**
     * 获取 RSAPublicKey
     *
     * @param pubKey base64加密公钥
     */
    private static RSAPublicKey getRSAPublicKey(String pubKey) {
        RSAPublicKey publicKey = null;
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(pubKey, 0));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }

    /**
     * 获取 RSAPrivateKey
     *
     * @param priKey base64加密私钥
     */
    private static RSAPrivateKey getRSAPrivateKey(String priKey) {
        RSAPrivateKey privateKey = null;
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(priKey, 0));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return privateKey;
    }

}
